<template>
	<div class="wrap">
		<div id="myChart" :style="{width: '600px', height: '400px'}"></div>
		<div id="main"></div>
	</div>
</template>

<script>
	//按需引入
	import echarts from 'echarts'
	import axios from 'axios'
	export default {
		name: 'Echarts',
		data() {
			return {
				itemId: [],
				itemName: [],
				unselected: [],
				selected: []
			}
		},
		created() {
			axios({
				//请求地址
				url: 'http://localhost:8080/axios/selectAllId.do',
				//请求方式
				method: 'post',
			}).then(
				res => {
					//this.itemName = res.data.ids
					let j = 0;
					for (var i = 0; i < res.data.ids.length; i++) {
						j++
						if (j <= 5) {
							this.itemId.push(res.data.ids[i].id)
							this.itemName.push(res.data.ids[i].coursename)
						}
					}
					this.loaded();
				},
				err => {
					console.log(err.message)
				}
			)
		},
		computed: {
			option() {
				return {
					title: {
						text: '选课人数对比',
						left: 'center',
						top: 20,
						textStyle: {
							color: '#555555'
						}
					},
					xAxis: {
						data: this.itemName
					},
					yAxis: {},
					series: [{
							type: 'bar',
							data: [{
									value: this.selected[0],
									itemStyle: {
										color: "#3fb1e3"
									}
								},
								{
									value: 3,
									itemStyle: {
										color: "#555555"
									}
								},
								{
									value: 5,
									itemStyle: {
										color: "#3fb1e3"
									}
								},
								{
									value: 7,
									itemStyle: {
										color: "#3fb1e3"
									}
								},
								{
									value: 8,
									itemStyle: {
										color: "#c4ebad"
									}
								},
							]
						},
						{
							type: 'bar',
							data: this.unselected
						}
					]
				}
			}
		},
		methods: {
			loaded() {
				var a = 0;
				for (var k = 0; k < 5; k++) {
					axios({
						//请求地址
						url: 'http://localhost:8080/axios/calculation?id=' + this.itemId[k],
						//请求方式
						method: 'GET',
					}).then(
						res => {
							a++
							this.unselected.push(res.data.unselected)
							this.selected.push(res.data.selected)
							if(a == 5){
								// 基于准备好的dom，初始化echarts实例
								let echarts = require('echarts')
								let myChart = echarts.init(document.getElementById('myChart'))
								// 绘制图表
								myChart.setOption(this.option);
							}
							
						},
						err => {
							console.log(err.message)
						}
					)
				}

			}
		}
		/*
		//请求完成之后才能填充动态数据
		 mounted() {
			// 基于准备好的dom，初始化echarts实例
			let echarts = require('echarts')
			let myChart = echarts.init(document.getElementById('myChart'))
			// 绘制图表
			myChart.setOption(this.option);
		}, */
	}
</script>
<style scoped="scoped">
	.wrap {
		margin: 0 auto;
		width: 60%;
	}
</style>
